package com.micl.fileserver.tools;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Objects;
import java.util.UUID;

@Component
public class FileSystemTools {

    @Value(value = "${micl.upload.file.path.temp}")
    private String decryptFilePath;
    @Value(value = "${micl.upload.file.path}")
    private String mergeFilePath;

    private String extensionName = ".part";

    public String makeDirWithUUID() {
        String uuid = UUID.randomUUID().toString();
        File folder = new File(decryptFilePath + uuid);
        folder.mkdirs();
        return uuid;
    }

    public boolean checkFileExist(String path) {
        return new File(path).exists();
    }

    public boolean checkPartExist(String uuid, String fileName) {
        return checkFileExist(decryptFilePath + uuid + "/" + fileName + extensionName);
    }

    public void storeFileByStream(InputStream inputStream, String uuid, String fileName) throws IOException {
        File outFile = new File(decryptFilePath + uuid, fileName + extensionName);
        FileUtils.copyInputStreamToFile(inputStream, outFile); // 将流复制到文件
    }

    public boolean checkPartCounts(String uuid, int count) {
        File folder = new File(decryptFilePath + uuid);
        return folder.isDirectory() && Objects.requireNonNull(folder.listFiles()).length == count;
    }

    public File mergeFileByUUID(String uuid, String fileName, int count) throws IOException {
        File folder = new File(decryptFilePath + uuid);
        if (!folder.isDirectory()) {
            throw new IOException("分片文件夹不存在");
        }

        File mergeFolder = new File(mergeFilePath);
        if (!mergeFolder.exists()) {
            mergeFolder.mkdirs();
        }
        if (!mergeFolder.isDirectory()) {
            throw new IOException("合并文件夹命名冲突，请人工解决");
        }

        File mergeFile = new File(mergeFilePath, uuid + "_" + fileName);
        FileOutputStream outputStream = new FileOutputStream(mergeFile, true);

        for (int i = 0; i < count; i++) {
            File partFile = new File(folder, i + ".part");
            FileUtils.copyFile(partFile, outputStream); //copyFile方法在同一个文件夹复制文件
        }
        outputStream.close();
//        FileUtils.deleteDirectory(folder);
        return mergeFile;
    }
}
